const mongoose = require("mongoose");
const { nanoid } = require('nanoid');
const muserSchema = new mongoose.Schema({
    nickname: {
        type: String,
    },
    username: {
        type: String,
        unique: true, // 确保用户名唯一
        required: true,
    },
    roles: [{
        type: mongoose.Schema.Types.ObjectId,
        required: false,
        ref: 'role'
    }],
    order: {
        type: Number,
        default: 0
    },
    disabled: {
        type: Boolean,
        default: false
    },
    avatar: {
        type: String,
        default: `nan.png`
    },
    phone: {
        type: String,
    },
    email: {
        type: String,
    },
    sex: {
        type: Number,
        default: 2
    },
    password: {
        type: String,
        default: '111'
    },
    money: {
        type: Number,
        default: 100000
    },
     usedCoupons: [{
        couponId: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "coupon"
        },
        usedCount: {
            type: Number,
            default: 0
        }
    }]
});

// 在保存前生成随机用户名和加密密码
muserSchema.pre('save', async function (next) {
    const user = this;
    // 如果是新用户，则生成随机用户名
    if (this.isNew) {
        let generatedUsername;
        do {
            generatedUsername = `user_${nanoid(8)}`; // 生成一个随机的用户名
            // 检查生成的用户名是否已经存在
            const existingUser = await this.constructor.findOne({ nickname: generatedUsername });
            if (!existingUser) break;
        } while (true);

        user.nickname = generatedUsername;

    }

    next();
});


const muser = mongoose.model("muser", muserSchema);
module.exports = {
    muser
};
